// @Author miaoqing
// @Date 2024/03/04 10:54:00
// @Desc
package logic

import (
	"core/command"
	"core/component/logger"
	"core/network"
	"sync"
)

type CenterClient struct {
	tcpClient *network.TcpClient
	onMsg     sync.Once
	srvID     string
	srvAddr   string
}

func (cc *CenterClient) checkConnect(addr string) {
	if cc.tcpClient.IsRunning() {
		return
	}
	if err := cc.tcpClient.Connect(addr); err != nil {
		logger.Error("[连接] Online->Center连接失败")
		return
	}
	cc.onMsg.Do(cc.registerCenterHandler)
	cc.msgToGateway()
	logger.Infof("[连接] Online->Center连接成功 SrvID:%v srvAddr:%v", cc.srvID, cc.srvAddr)
}

func (cc *CenterClient) msgToGateway() {
	msgSend := &command.RegisterToCenter{
		//Msgids:     pc.msgID,
		ServerID:   ServerInstance().id,
		ProcIndex:  uint32(ServerInstance().processIdx),
		ServerAddr: ServerInstance().httpAddr,
	}
	cc.sendMsg(command.Command_RegisterToCenter_Server, msgSend)
}

func (cc *CenterClient) registerCenterHandler() {
	cc.tcpClient.Router.Register(uint16(command.CenterCommand_CenterMsgToOnline_Center), cc.centerMessageQueueHandler)
}

func (cc *CenterClient) OnCloseCallBack() {

}

func (cc *CenterClient) sendMsg(cmd command.Command, msg interface{}) bool {
	return cc.tcpClient.AsyncSend(uint16(cmd), msg)
}

func (cc *CenterClient) sendCenterMsg(cmd command.CenterCommand, msg interface{}) bool {
	return cc.tcpClient.AsyncSend(uint16(cmd), msg)
}
